(function() {
	var STK = (function() {
		var spec = {
			dependCacheList : {},
			importCacheStore : {},
			importCacheList : [],
			jobsCacheList : []
		};
		var that = {};
		var lastPoint = 1;
		var baseURL = "";
		var errorInfo = [];
		var register = function(ns, maker) {
			var path = ns.split(".");
			var curr = that;
			for ( var i = 0, len = path.length; i < len; i += 1) {
				if (i == len - 1) {
					if (curr[path[i]] !== undefined) {
						throw ns + "has been register!!!"
					}
					curr[path[i]] = maker(that);
					return true
				}
				if (curr[path[i]] === undefined) {
					curr[path[i]] = {}
				}
				curr = curr[path[i]]
			}
		};
		var checkPath = function(ns) {
			var list = ns.split(".");
			var curr = that;
			for ( var i = 0, len = list.length; i < len; i += 1) {
				if (curr[list[i]] === undefined) {
					return false
				}
				curr = curr[list[i]]
			}
			return true
		};
		var checkDepend = function() {
			for ( var k in spec.dependCacheList) {
				var loaded = true;
				for ( var i = 0, len = spec.dependCacheList[k]["depend"].length; i < len; i += 1) {
					if (!checkPath(spec.dependCacheList[k]["depend"][i])) {
						loaded = false;
						break
					}
				}
				if (loaded) {
					register.apply(that, spec.dependCacheList[k]["args"]);
					delete spec.dependCacheList[k];
					setTimeout(function() {
						checkDepend()
					}, 25)
				}
			}
		};
		var E = function(id) {
			if (typeof id === "string") {
				return document.getElementById(id)
			} else {
				return id
			}
		};
		var addEvent = function(sNode, sEventType, oFunc) {
			var oElement = E(sNode);
			if (oElement == null) {
				return
			}
			sEventType = sEventType || "click";
			if ((typeof oFunc).toLowerCase() != "function") {
				return
			}
			if (oElement.attachEvent) {
				oElement.attachEvent("on" + sEventType, oFunc)
			} else {
				if (oElement.addEventListener) {
					oElement.addEventListener(sEventType, oFunc, false)
				} else {
					oElement["on" + sEventType] = oFunc
				}
			}
		};
		that.inc = function(ns, undepended) {
			if (!spec.importCacheList) {
				spec.importCacheList = []
			}
			for ( var i = 0, len = spec.importCacheList.length; i < len; i += 1) {
				if (spec.importCacheList[i] === ns) {
					if (!undepended) {
						spec.importCacheList.push(ns)
					}
					return false
				}
			}
			if (!undepended) {
				spec.importCacheList.push(ns)
			}
			spec.importCacheStore[ns] = false;
			var js = document.createElement("SCRIPT");
			js.setAttribute("type", "text/javascript");
			js.setAttribute("src", baseURL + ns.replace(/\./ig, "/") + ".js");
			js.setAttribute("charset", "utf-8");
			js[that.IE ? "onreadystatechange" : "onload"] = function() {
				if (!that.IE || this.readyState.toLowerCase() == "complete"
						|| this.readyState.toLowerCase() == "loaded") {
					lastPoint = spec.importCacheList.length;
					spec.importCacheStore[ns] = true;
					checkDepend()
				}
			};
			document.getElementsByTagName("HEAD")[0].appendChild(js)
		};
		that.register = function(ns, maker, shortName) {
			spec.dependCacheList[ns] = {
				args : arguments,
				depend : spec.importCacheList.slice(lastPoint,
						spec.importCacheList.length),
				"short" : shortName
			};
			lastPoint = spec.importCacheList.length;
			checkDepend()
		};
		that.regShort = function(sname, sfun) {
			if (that[sname] !== undefined) {
				throw sname + ":show has been register"
			}
			that[sname] = sfun
		};
		that.setBaseURL = function(url) {
			baseURL = url
		};
		that.getErrorInfo = function() {
			return errorInfo
		};
		that.IE = /msie/i.test(navigator.userAgent);
		that.E = E;
		that.C = function(tagName) {
			var dom;
			tagName = tagName.toUpperCase();
			if (tagName == "TEXT") {
				dom = document.createTextNode("")
			} else {
				if (tagName == "BUFFER") {
					dom = document.createDocumentFragment()
				} else {
					dom = document.createElement(tagName)
				}
			}
			return dom
		};
		that.Ready = (function() {
			var funcList = [];
			var inited = false;
			var exec_func_list = function() {
				if (inited == true) {
					return
				}
				inited = true;
				for ( var i = 0, len = funcList.length; i < len; i++) {
					if ((typeof funcList[i]).toLowerCase() == "function") {
						funcList[i].call()
					}
				}
				funcList = []
			};
			if (document.attachEvent && window == window.top) {
				(function() {
					try {
						document.documentElement.doScroll("left")
					} catch (e) {
						setTimeout(arguments.callee, 0);
						return
					}
					exec_func_list()
				})()
			} else {
				if (document.addEventListener) {
					addEvent(document, "DOMContentLoaded", exec_func_list)
				} else {
					if (/WebKit/i.test(navigator.userAgent)) {
						(function() {
							if (/loaded|complete/.test(document.readyState
									.toLowerCase())) {
								exec_func_list();
								return
							}
							setTimeout(arguments.callee, 25)
						})()
					}
				}
			}
			addEvent(window, "load", exec_func_list);
			return function(oFunc) {
				if (inited == true
						|| (/loaded|complete/).test(document.readyState
								.toLowerCase())) {
					if ((typeof oFunc).toLowerCase() == "function") {
						oFunc.call()
					}
				} else {
					funcList.push(oFunc)
				}
			}
		})();
		return that
	})();
	$Import = STK.inc;
	STK.register("core.evt.addEvent", function($) {
		return function(sNode, sEventType, oFunc) {
			var oElement = $.E(sNode);
			if (oElement == null) {
				return false
			}
			sEventType = sEventType || "click";
			if ((typeof oFunc).toLowerCase() != "function") {
				return
			}
			if (oElement.attachEvent) {
				oElement.attachEvent("on" + sEventType, oFunc)
			} else {
				if (oElement.addEventListener) {
					oElement.addEventListener(sEventType, oFunc, false)
				} else {
					oElement["on" + sEventType] = oFunc
				}
			}
			return true
		}
	});
	STK.register("core.evt.removeEvent", function($) {
		return function(el, evType, func, useCapture) {
			var _el = $.E(el);
			if (_el == null) {
				return false
			}
			if (typeof func != "function") {
				return false
			}
			if (_el.removeEventListener) {
				_el.removeEventListener(evType, func, useCapture)
			} else {
				if (_el.detachEvent) {
					_el.detachEvent("on" + evType, func)
				} else {
					_el["on" + evType] = null
				}
			}
			return true
		}
	});
	STK
			.register(
					"core.evt.getEvent",
					function($) {
						return function() {
							if ($.IE) {
								return window.event
							} else {
								if (window.event) {
									return window.event
								}
								var o = arguments.callee.caller;
								var e;
								var n = 0;
								while (o != null && n < 40) {
									e = o.arguments[0];
									if (e
											&& (e.constructor == Event || e.constructor == MouseEvent)) {
										return e
									}
									n++;
									o = o.caller
								}
								return e
							}
						}
					});
	STK.register("core.evt.stopEvent", function($) {
		return function(e) {
			var ev = e ? e : $.core.evt.getEvent();
			if ($.IE) {
				ev.cancelBubble = true;
				ev.returnValue = false
			} else {
				ev.preventDefault();
				ev.stopPropagation()
			}
			return false
		}
	});
	STK
			.register(
					"core.util.listener",
					function($) {
						return (function() {
							var dispatchList = {};
							var topWindow;
							var fireTaskList = [];
							var fireTaskTimer;
							function runFireTaskList() {
								if (fireTaskList.length == 0) {
									return
								}
								clearTimeout(fireTaskTimer);
								var curFireTask = fireTaskList.splice(0, 1)[0];
								curFireTask.func.call(curFireTask.func,
										curFireTask.data);
								fireTaskTimer = setTimeout(runFireTaskList, 25)
							}
							var dispatch = {
								conn : function() {
									var win = window;
									while (win != top) {
										win = win.parent;
										if (win.STK
												&& win.STK["core"]
												&& win.STK["core"]["util"]
												&& win.STK["core"]["util"]["listener"] != null) {
											topWindow = win
										}
									}
								},
								register : function(sChannel, sEventType,
										fCallBack) {
									if (topWindow != null) {
										topWindow.STK["core"]["util"]["listener"]
												.register(sChannel, sEventType,
														fCallBack)
									} else {
										dispatchList[sChannel] = dispatchList[sChannel]
												|| {};
										dispatchList[sChannel][sEventType] = dispatchList[sChannel][sEventType]
												|| [];
										dispatchList[sChannel][sEventType]
												.push(fCallBack)
									}
								},
								fire : function(sChannel, sEventType, oData) {
									if (topWindow != null) {
										topWindow.listener.fire(sChannel,
												sEventType, oData)
									} else {
										var funcArray;
										var i, len;
										if (dispatchList[sChannel]
												&& dispatchList[sChannel][sEventType]
												&& dispatchList[sChannel][sEventType].length > 0) {
											funcArray = dispatchList[sChannel][sEventType];
											for (i = 0, len = funcArray.length; i < len; i++) {
												fireTaskList.push({
													func : funcArray[i],
													data : oData
												})
											}
											runFireTaskList()
										}
									}
								},
								list : function() {
									return dispatchList
								}
							};
							return dispatch
						})()
					});
	var listener = STK.core.util.listener;
	var currentUser = null;
	var loadCurrentUser = function(callback) {
		callback = callback || function() {
		};
		if (currentUser) {
			callback(currentUser);
			return
		}
		WB.client
				.parseCMD(
						"/account/verify_credentials.json",
						function(sResult, bStatus) {
							if (!bStatus) {
								callback(false);
								return
							}
							if (sResult
									&& (sResult.error_code == "400" || sResult.error_code == "403")) {
								callback(false);
								return
							}
							currentUser = sResult;
							try {
								callback(sResult)
							} catch (e) {
							}
						}, {}, {
							method : "post"
						})
	};
	var connectButton = function(oBtn, oCallBack) {
		oCallBack = oCallBack || {};
		oBtn = STK.E(oBtn);
		var btn = STK.C("div");
		var oBtnClick = function() {
			WB.connect.login(function() {
				_is_connect()
			});
			STK.core.evt.stopEvent()
		};
		var listenerLogin = function(oData) {
			btn.innerHTML = "";
			btn.className = "weibo_widget_connect_icon";
			STK.core.evt.removeEvent(btn, "click", oBtnClick);
			var linkScreenname = STK.C("a");
			linkScreenname.href = "http://weibo.com/" + oData.json.id;
			linkScreenname.setAttribute("target", "_blank");
			linkScreenname.innerHTML = oData.json.screen_name;
			var linkLogout = STK.C("a");
			linkLogout.href = "javascript:;";
			linkLogout.className = "weibo_widget_connect_disconnect";
			linkLogout.innerHTML = "退出";
			STK.core.evt.addEvent(linkLogout, "click", function() {
				WB.connect.logout(function() {
					_no_connect();
					if (oCallBack.logout) {
						oCallBack.logout()
					}
				});
				currentUser = null;
				STK.core.evt.stopEvent()
			});
			btn.appendChild(linkScreenname);
			btn.appendChild(linkLogout)
		};
		var listenerLogout = function() {
			btn.innerHTML = "";
			btn.className = "weibo_widget_connect_btn";
			STK.core.evt.addEvent(btn, "click", oBtnClick)
		};
		var _is_connect = function() {
			loadUserCB = function(json) {
				if (json === false) {
					_no_connect();
					return
				}
				var data = {
					json : json
				};
				if (oCallBack.login) {
					oCallBack.login(json)
				}
				listener.fire("connectButton", "listenerLogin", data)
			};
			loadCurrentUser(loadUserCB)
		};
		var _no_connect = function() {
			listener.fire("connectButton", "listenerLogout")
		};
		btn.className = "weibo_widget_connect_btn";
		listener.register("connectButton", "listenerLogin", listenerLogin);
		listener.register("connectButton", "listenerLogout", listenerLogout);
		listener.register("followLogin", "listenerLogin", _is_connect);
		oBtn.appendChild(btn);
		if (WB.connect.checkLogin()) {
			_is_connect()
		} else {
			listenerLogout()
		}
	};
	var followButton = function(uid, oBtn) {
		uid = Number(uid);
		oBtn = STK.E(oBtn);
		if (isNaN(uid)) {
			return
		}
		var linkButton = document.createElement("a");
		linkButton.href = "javascript:;";
		var _is_login = function() {
			_is_loading();
			loadCurrentUser(function(json) {
				if (json === false) {
					_add_follow();
					return
				}
				if (uid == json.id) {
					listener.fire("followButton", uid + "_is_me")
				} else {
					_load_friendships()
				}
			})
		};
		var _add_follow = function() {
			linkButton.onclick = function() {
				WB.connect.login(function() {
					_load_friendships(_create_friendships);
					listener.fire("followLogin", "listenerLogin")
				});
				STK.core.evt.stopEvent()
			};
			linkButton.className = "weibo_widget_btn";
			linkButton.innerHTML = "<em>加关注</em>"
		};
		var _has_follow = function() {
			linkButton.onclick = null;
			linkButton.className = "weibo_widget_btn_dis";
			linkButton.innerHTML = "<em>已关注</em>"
		};
		var _each_follow = function() {
			linkButton.onclick = null;
			linkButton.className = "weibo_widget_btn_dis";
			linkButton.innerHTML = "<em>互相关注</em>"
		};
		var _is_me = function() {
			linkButton.onclick = null;
			linkButton.className = "weibo_widget_btn_dis";
			linkButton.innerHTML = "<em>我自己</em>"
		};
		var _is_loading = function() {
			linkButton.onclick = null;
			linkButton.className = "weibo_widget_btn_dis";
			linkButton.innerHTML = '<em><span class="weibo_widget_btn_loading"></span></em>'
		};
		var _load_friendships = function(cb) {
			cb = cb || _add_follow;
			WB.client.parseCMD("/friendships/show.json", function(sResult,
					bStatus) {
				if (!bStatus) {
					listener.fire("followButton", uid + "_add_follow");
					return
				}
				if (sResult.source.following) {
					if (sResult.source.followed_by) {
						listener.fire("followButton", uid + "_each_follow")
					} else {
						listener.fire("followButton", uid + "_has_follow")
					}
				} else {
					cb()
				}
			}, {
				target_id : uid
			}, {
				method : "post"
			})
		};
		var _create_friendships = function() {
			WB.client
					.parseCMD(
							"/friendships/create.json",
							function(sResult, bStatus) {
								if (!bStatus) {
									listener.fire("followButton", uid
											+ "_add_follow");
									return
								}
								if (sResult
										&& (sResult.error_code == "400" || sResult.error_code == "403")) {
									listener.fire("followButton", uid
											+ "_add_follow");
									return
								}
								_load_friendships()
							}, {
								id : uid
							}, {
								method : "post"
							})
		};
		listener.register("followButton", uid + "_add_follow", _add_follow);
		listener.register("followButton", uid + "_has_follow", _has_follow);
		listener.register("followButton", uid + "_each_follow", _each_follow);
		listener.register("followButton", uid + "_is_me", _is_me);
		listener.register("connectButton", "listenerLogin", _is_login);
		listener.register("connectButton", "listenerLogout", _add_follow);
		if (WB.connect.checkLogin()) {
			_is_login()
		} else {
			_add_follow()
		}
		//oBtn.appendChild(linkButton)
	};
	that = {};
	that.connectButton = connectButton;
	that.followButton = followButton;
	WB.regist("widget.base", that)
})();